//
//  QKClipsDetailController.m
//  EasyIOS
//
//  Created by ChiCo on 2017/5/3.
//  Copyright © 2017年 EasyIOS. All rights reserved.
//

#import "QKClipsDetailController.h"
#import <Photos/Photos.h>
#import "UIImage+Orientation.h"

@interface QKClipsDetailController () <UIScrollViewDelegate>
/**
 * 裁剪窗口
 */
@property (nonatomic,strong)UIView *frameView;
/**
 * 底部滚动视图
 */
@property (nonatomic,strong)UIScrollView *bodyScrollView;
/**
 * 相片显示视图
 */
@property (nonatomic,strong)UIImageView *photoView;
/**
 * 截图区域的宽高比例，不可以超过屏幕的宽高比[没做过长图片的截取]
 */
@property (nonatomic,assign)CGFloat radio;
/**
 * 截图完成
 */
@property (nonatomic,copy) void (^finish)(UIImage *image);
/**
 * 从相册获取的图片资源
 */
@property (nonatomic,strong)PHAsset *asset;
@end

@implementation QKClipsDetailController

- (instancetype)initWithAsset:(PHAsset *)asset
                        radio:(CGFloat)radio
                       finish:(void (^)(UIImage *))finish
{
    self = [super init];
    if (self) {
        self.finish = finish;
        self.radio = radio;
        self.asset = asset;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self layoutSubViews];
    
}


- (void)layoutSubViews
{
    [self.view setBackgroundColor:[UIColor blackColor]];

    CGFloat pixW = self.asset.pixelWidth;
    CGFloat pixH = self.asset.pixelHeight;
    CGFloat maskH = self.radio * KScreenWidth;
    CGFloat topH = (KScreenHeight - maskH)/2;
    CGSize imageSize = CGSizeMake(pixW, pixH);
    
    //图片的显示区域不小于截图窗口区域
    CGFloat imageScale = MAX(KScreenWidth/imageSize.width, maskH/imageSize.height);
    CGSize scaledSize = (CGSize){floorf((float)imageSize.width * (float)imageScale), floorf((float)imageSize.height * (float)imageScale)};
    
    CGRect screenR = CGRectMake(0, 0, KScreenWidth, KScreenHeight);
    self.bodyScrollView = [[UIScrollView alloc] initWithFrame:screenR];
    [self.view addSubview:self.bodyScrollView];
    [self.bodyScrollView setContentSize:scaledSize];
    self.bodyScrollView.minimumZoomScale = 1.0f;
    self.bodyScrollView.maximumZoomScale = 5.0f;
    [self.bodyScrollView setContentInset:UIEdgeInsetsMake(topH, 0, topH, 0)];
    if (@available(iOS 11.0, *)) {
        self.bodyScrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        [self setAutomaticallyAdjustsScrollViewInsets:NO];
    }
    if (KScreenWidth < scaledSize.width - FLT_EPSILON ||
        maskH < scaledSize.height - FLT_EPSILON)
    {
        //滚到中间
        CGPoint offset = CGPointZero;
        offset.x = floorf((float)(scaledSize.width - KScreenWidth) * 0.5f);
        offset.y = floorf((float)(scaledSize.height - KScreenHeight) * 0.5f);
        [self.bodyScrollView setContentOffset:offset];
        
    }
    
    self.photoView = [[UIImageView alloc] initWithFrame:(CGRect){CGPointZero,scaledSize}];
    [self.bodyScrollView addSubview:self.photoView];
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    [options setResizeMode:PHImageRequestOptionsResizeModeExact];
    [options setDeliveryMode:PHImageRequestOptionsDeliveryModeHighQualityFormat];
    [options setNetworkAccessAllowed:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    @weakify(self);
    [[PHImageManager defaultManager] requestImageForAsset:self.asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info)
     {
         @strongify(self);
         [MBProgressHUD hideHUDForView:self.view animated:YES];
         [self.photoView setImage:result];
     }];
    [self.bodyScrollView setDelegate:self];
    
    
    [self setUpMask:topH
              maskH:maskH];
    [self setUpBottomView];
    
    //滚动视图不需要全屏切换
    [self setAutomaticallyAdjustsScrollViewInsets:NO];
    // Fallback on earlier versions
}


- (void)setUpMask:(CGFloat)topH
            maskH:(CGFloat)maskH
{
    
    //topMask
    UIView *topMask = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, topH)];
    [topMask setBackgroundColor:[UIColor colorWithHexString:@"#000000"
                                                      alpha:0.5f]];
    [topMask setUserInteractionEnabled:NO];
    [self.view addSubview:topMask];
    
    
    
    self.frameView = [[UIView alloc] initWithFrame:CGRectMake(0, topH, KScreenWidth,maskH)];
    
    //bottomMask
    UIView *bottomMask = [[UIView alloc] initWithFrame:CGRectMake(0, KScreenHeight-topH, KScreenWidth, topH)];
    [bottomMask setUserInteractionEnabled:NO];
    [bottomMask setBackgroundColor:[UIColor colorWithHexString:@"#000000"
                                                         alpha:0.5f]];
    [self.view addSubview:bottomMask];
    
}

- (void)setUpBottomView
{
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, KScreenHeight-50, KScreenWidth, 50)];
    [bottomView setBackgroundColor:[UIColor colorWithHexString:@"#000000"
                                                         alpha:0.5]];
    [self.view addSubview:bottomView];
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [bottomView addSubview:cancelButton];
    [cancelButton setFrame:CGRectMake(0, 0, 70, 50)];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancelButton addTarget:self
                     action:@selector(cancelAction)
           forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [bottomView addSubview:sureButton];
    [sureButton setFrame:CGRectMake(KScreenWidth-70, 0, 70, 50)];
    [sureButton setTitle:@"确定" forState:UIControlStateNormal];
    [sureButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sureButton addTarget:self
                   action:@selector(surelAction)
         forControlEvents:UIControlEventTouchUpInside];
}

- (void)cancelAction
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)surelAction
{
    UIImage *soceImage = [self.photoView.image fixOrientationUp];
    UIEdgeInsets insert = self.bodyScrollView.contentInset;
    CGFloat scale;
    CGFloat imgeScale = soceImage.size.width / soceImage.size.height;
    CGFloat frameScale = self.frameView.frame.size.width/self.frameView.frame.size.height;
    if (imgeScale > frameScale) {
        scale = (soceImage.size.height/self.bodyScrollView.zoomScale/self.frameView.frame.size.height);
    } else {
        scale = (soceImage.size.width/self.bodyScrollView.zoomScale/KScreenWidth);
    }
    CGRect cropRect = CGRectMake((insert.left + self.bodyScrollView.contentOffset.x)*scale, (insert.top + self.bodyScrollView.contentOffset.y)*scale, KScreenWidth*scale, self.frameView.frame.size.height*scale);
    //不截取黑边处理
    CGSize imgeSize = soceImage.size;
    if (CGRectGetMaxX(cropRect) > imgeSize.width) {
        //最多截取到右边
        cropRect.origin.x = imgeSize.width - cropRect.size.width;
    } else {
        if (cropRect.origin.x < 0) {
            //最多截到最左边
            cropRect.origin.x = 0;
        }
    }
    
    
    if (CGRectGetMaxY(cropRect) > imgeSize.height) {
        //最多截取到下边
        cropRect.origin.y = imgeSize.height - cropRect.size.height;
    } else {
        if (cropRect.origin.y < 0) {
            //最多截到最上边
            cropRect.origin.y = 0;
        }
    }
    
    CGImageRef imageRef = CGImageCreateWithImageInRect(soceImage.CGImage, cropRect);
    UIImage *resultImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    if (resultImage.size.width > 1242) {
        //图片过大，plus 能够显示的就足够了
        UIGraphicsBeginImageContext(CGSizeMake(1242, 1242*self.radio));
        [resultImage drawInRect:CGRectMake(0, 0,1242, 1242*self.radio)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    
    if (self.finish) {
        self.finish(resultImage);
    }
    [self.navigationController popViewControllerAnimated:YES];
}



- (BOOL)prefersStatusBarHidden
{
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.photoView;
}

@end
